import { defineStore } from 'pinia'
import { asyncRoutes } from '@/router'
import { RouteRecordRaw } from 'vue-router'
import { generateMenus } from '@/router/helper/menuHelper'
import { filterRoutes, flatMultiLevelRoutes } from '@/router/helper/routeHelper'
import { ENABLE_AUTH, ROUTE_MODE } from '@/settings'

interface PermissionsStateProps {
  menu: Array<RouteRecordRaw>
  routes: Array<RouteRecordRaw>
}
export const usePermissionsStore = defineStore('permissions', {
  state: ():PermissionsStateProps => {
    return {
      menu: [],
      routes: []
    }
  },
  actions: {
    async getRoutes (roles:Array<string>) {
      switch (ROUTE_MODE) {
        case 'FRONT':
          /** 前端模式 **/
          if (ENABLE_AUTH) {
            // 启用权限过滤
            this.routes = filterRoutes(asyncRoutes, roles)
          } else {
            this.routes = asyncRoutes
          }
          break
        default:
          this.routes = []
          console.error('【ROUTE_MODE】无效的路由模式配置')
          break
      }
      // 生成导航菜单并储存
      this.menu = generateMenus(this.routes)

      // 生成动态路由 并返回
      this.routes = flatMultiLevelRoutes(this.routes)
      return this.routes
    }
  },
  persist: {
    paths: ['menu'],
    storage: sessionStorage
  }
})

export default usePermissionsStore
